/**
 * Created by cchen on 2015/5/19.
 */


'use strict';
angular.module('backofficeApp.lotteryActivity.controller', []).
    controller('lotteryActivityCtrl', ['$scope','$http','$location', function ($scope,$http,$location) {
        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];

        $scope.filter=function(){
            var params = {
                currentPage:$scope.currentPage,
                communityName:$scope.filter_community_name,
                activityName:$scope.filter_activity_name
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/lotteryList', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.list;
                $scope.totalPage = data.data.totalPage;
            }).error(function () {
            });
        }

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.filter();
        }

        $scope.getCommunitys = function (lotteryId) {
            $location.path('/getCommunitysByLotteryId/'+lotteryId);
        }

        $scope.getAwardList = function (lotteryId) {
            $location.path('/awardList/'+lotteryId);
        }

        $scope.editPrize = function (lotteryId) {
            $location.path('/getPrizeByLotteryId/'+lotteryId);
        }
        $scope.add = function () {
            $location.path('/addLottery');
        }
        $scope.update = function (lotteryId) {
            $location.path('/updateLottery/'+lotteryId);
        }
        $scope.delete = function (lotteryId) {
            var params = {lotteryId:lotteryId};
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/deleteLottery', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function () {
                $scope.filter();
            })
        }

        $scope.filter();

    }]).directive('mutau', function () {
        return {
            restrict: 'E',
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    }).controller('productCtrl', ['$scope','$http','$location', function ($scope,$http,$location) {
        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];

        $scope.filter=function(){
            var params = {
                currentPage:$scope.currentPage,
                productName:$scope.filter_product_name
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/productList', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.list;
                $scope.totalPage = data.data.totalPage;
            }).error(function () {
            });
        }

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.filter();
        }

        $scope.add=function(){
            $location.path('/addProduct');
        }

        $scope.update=function(id){
            $location.path('/updateProduct/'+id);
        }

        $scope.delete=function(id){
            var params = {
                id:id
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/deleteProduct', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function() {
                $scope.filter();
            });

        }

        $scope.filter();

    }]).directive('mutau', function () {
        return {
            restrict: 'E',
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    }).controller('addProductCtrl', ['$scope','$http','$location', function ($scope,$http,$location) {

        $scope.add = function(){
            var params = {
                productName:$scope.productName,
                inventory:$scope.inventory,
                type:$scope.type
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/addProduct', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            });
            $location.path('/productList');
        }

        $scope.cannel=function(){
              history.go(-1);
        }

    }]).controller('updateProductCtrl', ['$scope','$http','$location','$routeParams', function ($scope,$http,$location,$routeParams) {

        var params = {
            id:$routeParams.id
        };

        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/findProductById', params, {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (data) {
            $scope.productName = data.data[0].name;
            $scope.inventory = data.data[0].inventory;
            $scope.type = data.data[0].type;
        }).error(function () {
        });

        $scope.update = function(){
            var params = {
                id:$routeParams.id,
                inventoryType:$scope.inventoryType,
                updateInventory:$scope.updateInventory
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/updateProductInventory', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function () {
                $location.path('/productList');
            })
        }

        $scope.cannel=function(){
            history.go(-1);
        }

    }]).controller('getCommunitysCtrl', ['$scope','$http','$routeParams', function ($scope,$http,$routeParams) {
        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];

        $scope.filter=function(){
            var params = {
                currentPage:$scope.currentPage,
                lotteryId:$routeParams.lotteryId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getCommunitysByLotteryId', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.list;
                $scope.totalPage = data.data.totalPage;
            }).error(function () {
            });
        }

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.filter();
        }

        $scope.delete = function(communityId){
            var params = {
                communityId:communityId,
                lotteryId:$routeParams.lotteryId
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/deleteLotteryCommunityMap', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function () {
                $scope.filter();
            });
        }

        $scope.filter();

    }]).directive('mutau', function () {
        return {
            restrict: 'E',
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    }).controller('prizeListCtrl', ['$scope','$http','$routeParams','$location', function ($scope,$http,$routeParams,$location) {
        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];
        $scope.lotteryId = $routeParams.lotteryId;

        $scope.filter=function(){
            var params = {
                currentPage:$scope.currentPage,
                lotteryId:$routeParams.lotteryId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getPrizeByLotteryId', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.list;
                $scope.totalPage = data.data.totalPage;
            }).error(function () {
            });
        }

        $scope.update = function (prizeId,lotteryId) {
            $location.path('/updatePrize/'+prizeId+'/'+lotteryId);
        }

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.filter();
        }

        $scope.add = function (lotteryId) {
            $location.path('/addPrize/'+lotteryId);
        }

        $scope.delete = function(prizeId){
            var params = {
                prizeId:prizeId
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/deletePrize', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function () {
                $scope.filter();
            });
        }

        $scope.filter();

    }]).directive('mutau', function () {
        return {
            restrict: 'E',
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    }).controller('addPrizeCtrl', ['$scope','$http','$location','$routeParams', function ($scope,$http,$location,$routeParams) {

        var params = {};
        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getAllProduct', params, {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (data) {
            var productList = new Array();
            for(var i = 0 ; i < data.data.length ; i++){
                productList.push({value:data.data[i].id,name:data.data[i].name});
            }
            $scope.productList = productList;
        }).error(function () {
        });

        $scope.cannel=function(){
            history.go(-1);
        }

        $scope.add=function(){
            var params = {
                productId:$('#productId').val(),
                levelName:$scope.levelName,
                prizeCount:$scope.prizeCount,
                rewardCount:$scope.rewardCount,
                prizeLevel:$scope.prizeLevel,
                lotteryId:$routeParams.lotteryId
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/addPrize', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/getPrizeByLotteryId/'+$routeParams.lotteryId);
            }).error(function () {
            });
        }

    }]).controller('updatePrizeCtrl', ['$scope','$http','$location','$routeParams', function ($scope,$http,$location,$routeParams) {

        var params = {
            prizeId:$routeParams.prizeId
        };
        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getLotteryPrizeById', params, {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (data) {
            var prize = data.data[0];
            $scope.prizeName = prize.name;
            $scope.levelName = prize.level_name;
            $scope.prizeCount = prize.prize_count;
            $scope.rewardCount = prize.reward_count;
            $scope.prizeLevel = prize.prize_level;

        }).error(function () {
        });

        $scope.cannel=function(){
            history.go(-1);
        }

        $scope.update=function(){
            var params = {
                prizeId:$routeParams.prizeId,
                levelName:$scope.levelName,
                prizeCount:$scope.prizeCount,
                rewardCount:$scope.rewardCount,
                prizeLevel:$scope.prizeLevel
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/updateLotteryPrize', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/getPrizeByLotteryId/'+$routeParams.lotteryId);
            }).error(function () {
            });
        }

    }]).controller('awardListCtrl', ['$scope','$http','$location','$routeParams', function ($scope,$http,$location,$routeParams) {
        $scope.currentPage = 1;
        $scope.totalPage = 0;
        $scope.pages = [];

        $scope.filter=function(){
            var params = {
                lotteryId:$routeParams.lotteryId,
                currentPage:$scope.currentPage
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getLotteryAward', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.resultList = data.data.list;
                $scope.totalPage = data.data.totalPage;
            }).error(function () {
            });
        }

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.filter();
        }

        $scope.filter();

    }]).directive('mutau', function () {
        return {
            restrict: 'E',
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };
            }
        };
    }).controller('addLotteryCtrl', ['$scope','$http','$location','$routeParams','CommunityService', function ($scope,$http,$location,$routeParams,communityService) {
        $scope.communityList = communityService.getAllCommunityService();


        function datePicker(id) {
            function d(id) {
                var self = this;
                $(id).datepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                    forceParse: false
                }).on('changeDate', function (e) {
                    self.date = e.date;
                });

            }

            d.prototype.getValue = function (isFrom) {

                if ($(id).val() == "") {
                    return undefined;
                }

                if (!this.date) {
                    return undefined
                }

                if (isFrom) {

                    return this.date.setHours(0, 0, 0, 0)
                }
                return this.date.setHours(23, 59, 59, 0)
            }
            var date = new d(id);
            return date;
        }

        $scope.beginTimeTemp = datePicker("#activityBeginTime");
        $scope.endTimeTemp = datePicker("#endTime");

        $scope.addCommunity = function () {
            //先判断是否有选中
            if (!$("#communitys option").is(":selected")) {
                alert("请选择需要移动的选项")
            }
            //获取选中的选项，删除并追加给对方
            else {
                $('#communitys option:selected').appendTo('#selCommunitys');
            }
        };

        //移到左边
        $scope.removeCommunity = function () {
            //先判断是否有选中
            if (!$("#selCommunitys option").is(":selected")) {
                alert("请选择需要移动的选项")
            }
            else {
                $('#selCommunitys option:selected').appendTo('#communitys');
            }
        };

        //全部移到右边
        $scope.addAllCommunity = function () {
            //获取全部的选项,删除并追加给对方
            $('#communitys option').appendTo('#selCommunitys');
        };

        //全部移到左边
        $scope.removeAllCommunity = function () {
            $('#selCommunitys option').appendTo('#communitys');
        };

        $scope.showManyCommunity = function () {
            $("#manyCommunity").show();
            $("#community").hide();
        };

        $scope.showOneCommunity = function () {
            $("#community").show();
            $("#manyCommunity").hide();
        }

        $scope.cannel=function(){
            $location.path('/lotteryList');
        }

        $scope.add = function () {

            if($scope.beginTimeTemp.getValue(true) > $scope.endTimeTemp.getValue(false)){
                alert("开始时间不能晚于结束时间，请修改");
                return ;
            }

            var communityIds = new Array();
            var chooseCommunity = $scope.chooseCommunity;
            if (chooseCommunity == null || chooseCommunity == 0){
              $('#selCommunitys option').each(function (i, selected) {
                    communityIds.push($(selected).val());
                });
            }else if(chooseCommunity == 1){
                communityIds.push($scope.oneCommunity);
            }
            var params = {
                activityName:$scope.activityName,
                communityIds:communityIds,
                limitCount:$scope.limitCount,
                activityDesc:$scope.activityDesc,
                ruleDesc:$scope.ruleDesc,
                activityBeginTime:$scope.beginTimeTemp.getValue(true),
                activityEndTime:$scope.endTimeTemp.getValue(false),
                isPublish:$scope.isPublish == null ? 1 : $scope.isPublish
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/addLottery', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/lotteryList');
            });
        }


    }]).controller('updateLotteryCtrl', ['$scope','$http','$location','$routeParams','CommunityService', function ($scope,$http,$location,$routeParams,communityService) {

        function getLocalTime(nS) {
            return new Date(parseInt(nS)).toLocaleString().substr(0,10)
        }

        var params = {
            lotteryId:$routeParams.lotteryId
        }
        $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getLotteryById', params, {
            headers: {'Content-Type': 'application/json;charset=utf-8'}
        }).success(function (data) {
            var lotteryActivity = data.data[0];
            $scope.activityName = lotteryActivity.activity_name;
            $scope.limitCount = lotteryActivity.lottery_limit;
            $scope.activityDesc = lotteryActivity.activity_desc;
            $scope.ruleDesc = lotteryActivity.rule_desc;
            $scope.activityBeginTime = getLocalTime(lotteryActivity.begin_time);
            $scope.endTime = getLocalTime(lotteryActivity.end_time);
        });

        function datePicker(id) {
            function d(id) {
                var self = this;
                $(id).datepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                    forceParse: false
                }).on('changeDate', function (e) {
                    self.date = e.date;
                });

            }

            d.prototype.getValue = function (isFrom) {

                if ($(id).val() == "") {
                    return undefined;
                }

                if (!this.date) {
                    return undefined
                }

                if (isFrom) {

                    return this.date.setHours(0, 0, 0, 0)
                }
                return this.date.setHours(23, 59, 59, 0)
            }
            var date = new d(id);
            return date;
        }

        $scope.beginTimeTemp = datePicker("#activityBeginTime");
        $scope.endTimeTemp = datePicker("#endTime");

        $scope.update=function(){
            var params = {
                lotteryId:$routeParams.lotteryId,
                activityName:$scope.activityName,
                limitCount:$scope.limitCount,
                activityDesc:$scope.activityDesc,
                ruleDesc:$scope.ruleDesc,
                activityBeginTime:$scope.beginTimeTemp.getValue(true),
                activityEndTime:$scope.endTimeTemp.getValue(false)
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/updateLottery', params, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/lotteryList');
            });

        };

        $scope.cannel=function(){
            $location.path('/lotteryList');
        }
    }]);